<?php
	/**
	 * 元宝(奖券)兑换奖品
	 */
    class ExchangeAward extends APIBase {
		
		public $tag = "ExchangeAward";
		
		public function before() {
			$this->initMysql();
			$this->initCacheRedis();
			return true;
		}
		
		public function logic() {
			if (!isset($this->param['award_id'])) {
				$this->returnError(300, 'award_id is needed');
			}
			
			if (!isset($this->param['mobile'])) {
				$this->returnError(300, 'mobile is needed');
			}
			
			$award = $this->cache_redis->hGetAll("haward:{$this->param['award_id']}");
			if (!$award) {
				$this->returnError(321, 'award_id is wrong');
			}
			
			$coin = $this->data_redis->hGet("hu:{$this->uid}", "coin");
			if ((int)$coin < (int)$award['coin'])	{
				$this->returnError(322, '对不起，您的奖券数不符合兑换条件');
			}
			
			//扣除coin
			$cur_coin = $this->data_redis->hincrBY("hu:{$this->uid}", "coin", 0 - $award['coin']);
			//插入奖品有待兑换记录表
			$this->InsertAwardRecord($this->uid, $this->param['award_id'], $award['name'], $award['coin'], $this->param['mobile']);
			$ret = array();			
			$ret['coin'] = $this->data_redis->hGet("hu:{$this->uid}", "coin");
			$ret['coin'] = (int)$ret['coin'];
			$this->returnData($ret);
		}
		
		public function InsertAwardRecord($uid, $award_id, $award_name, $coin, $mobile) {
			$now = time();
			$awardlog = array(
					'uid'=> $uid,
					'status' => 0,
					'coin'=> $coin,
					'award_id'=> $award_id,
					'award_name' =>$award_name,
					'mobile' => $mobile,									
					'create_time' => $now,
					'update_time' => $now
			);
				
			$this->mysql->insert("exg_award_record", $awardlog);
		}
		
        public function after() {
    		$this->deinitDataRedis();
			$this->deinitCacheRedis();
			$this->deinitMysql();
		}
    }
?>
